package com.ewhale.feitengguest.ui.user.task;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.ewhale.feitengguest.R;
import com.ewhale.feitengguest.dto.BannerDto;
import com.ewhale.feitengguest.dto.ClassificationDto;
import com.ewhale.feitengguest.dto.NavigationDto;
import com.ewhale.feitengguest.dto.RankDto;
import com.ewhale.feitengguest.dto.TabEntity;
import com.ewhale.feitengguest.dto.TaskListDto;
import com.ewhale.feitengguest.presenter.user.task.TaskPresenter;
import com.ewhale.feitengguest.ui.WebViewActivity;
import com.ewhale.feitengguest.ui.auth.LoginActivity;
import com.ewhale.feitengguest.ui.user.mine.InviteListActivity;
import com.ewhale.feitengguest.ui.user.task.adapter.TaskListAdpater;
import com.ewhale.feitengguest.ui.user.task.adapter.TipAdapter;
import com.ewhale.feitengguest.utils.GlideImageLoader;
import com.ewhale.feitengguest.view.user.task.TaskView;
import com.ewhale.feitengguest.widget.BannerLayout;
import com.ewhale.feitengguest.widget.ScreenTipDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.orhanobut.hawk.Hawk;
import com.simga.library.activity.MBaseFragment;
import com.simga.library.utils.HawkKey;
import com.simga.library.widget.CoustomRefreshView;
import com.sunfusheng.marqueeview.MarqueeView;
import com.youth.xframe.widget.loadingview.XLoadingView;

import java.util.ArrayList;
import java.util.List;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.OnClick;

public class TaskFragment extends MBaseFragment<TaskPresenter> implements TaskView {
    @BindView(R.id.bannerlayout)
    BannerLayout mBannerlayout;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.ref_layout)
    CoustomRefreshView mRefLayout;
    @BindView(R.id.lv_tip)
    RecyclerView mLvTip;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.lv_task)
    RecyclerView mList;
    @BindView(R.id.marqueeView)
    MarqueeView marqueeView;
    @BindView(R.id.topMainTab)
    CommonTabLayout topMainTab;
    @BindView(R.id.line)
    View line;

    private List<TaskListDto> datas = new ArrayList<>();
    private TaskListAdpater mAdpater;
    private int pageNum = 1;
    private List<String> imageUrl = new ArrayList<>();
    private TipAdapter tipAdapter;
    private List<BannerDto> mBannerList;
    private List<ClassificationDto> mDtoList;
    private int cateId;
    private ScreenTipDialog scereenDialog;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    @Override
    protected int getViewId() {
        return R.layout.fragment_task;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        presenter.getBannerList();
        presenter.getClassification();
        presenter.getNavigationList();
        presenter.getRanking();
    }

    @Override
    public void onStart() {
        super.onStart();
        marqueeView.startFlipping();
    }

    @Override
    public void onStop() {
        super.onStop();
        marqueeView.stopFlipping();
    }

    @Override
    protected void firstInit(Bundle savedInstanceState) {
        scereenDialog = new ScreenTipDialog(mContext);
        mBannerlayout.setImageLoader(new GlideImageLoader());

        tipAdapter = new TipAdapter();
        mLvTip.setLayoutManager(new GridLayoutManager(mContext, 4));
        mLvTip.setHasFixedSize(false);
        mLvTip.setNestedScrollingEnabled(false);
        mLvTip.setAdapter(tipAdapter);

        mAdpater = new TaskListAdpater(datas);
        mList.setLayoutManager(new GridLayoutManager(mContext, 2));
        mList.setHasFixedSize(false);
        mList.setNestedScrollingEnabled(false);
        mList.setAdapter(mAdpater);
    }

    @Override
    protected void initListener() {
        mRefLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                presenter.getBannerList();
                presenter.getClassification();
                presenter.getNavigationList();
                presenter.getRanking();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                pageNum++;
                presenter.getTaskList(pageNum, cateId);
            }
        });
        mBannerlayout.setOnBannerListener(position -> {
            if (mBannerList.get(position).getBannerType() == 2) {
                presenter.loadBannerDetail(mBannerList.get(position).getId(), position);
            } else if (mBannerList.get(position).getBannerType() == 1) {
                WebViewActivity.open(mContext, mBannerList.get(position).getTitle(), mBannerList.get(position).getUrl());
            } else if (mBannerList.get(position).getBannerType() == 4) {
                InviteListActivity.open(mContext);
            } else if (mBannerList.get(position).getBannerType() == 5) {
                if (!Hawk.get(HawkKey.IS_USER_LOGIN, false)) {
                    LoginActivity.open(mContext);
                    return;
                }
                SignInActivity.open(mContext);
            }
        });
        mAdpater.setOnItemClickListener((view, position) -> TaskDetailsActivity.open(mContext, datas.get(position).getId()));
        topMainTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position == 1) {
                    scereenDialog.setTipDatas(mDtoList);
                    scereenDialog.setCate(cateId);
                    scereenDialog.showAsDropDown(line);
                } else {
                    mTabEntities.clear();
                    mTabEntities.add(new TabEntity(mDtoList.get(0).getName(), 0, 0));
                    mTabEntities.add(new TabEntity("筛选任务", R.mipmap.home_arrow_up, R.mipmap.home_arrow_down));
                    topMainTab.setTabData(mTabEntities);
                    pageNum = 1;
                    cateId = mDtoList.get(0).getId();
                    presenter.getTaskList(pageNum, cateId);
                }
            }

            @Override
            public void onTabReselect(int position) {
                if (position == 1) {
                    scereenDialog.setTipDatas(mDtoList);
                    scereenDialog.setCate(cateId);
                    scereenDialog.showAsDropDown(line);
                } else {
                    mTabEntities.clear();
                    mTabEntities.add(new TabEntity(mDtoList.get(0).getName(), 0, 0));
                    mTabEntities.add(new TabEntity("筛选任务", R.mipmap.home_arrow_up, R.mipmap.home_arrow_down));
                    topMainTab.setTabData(mTabEntities);
                    pageNum = 1;
                    cateId = mDtoList.get(0).getId();
                    presenter.getTaskList(pageNum, cateId);
                }
            }
        });
        scereenDialog.setOnClickListener(item -> {
            pageNum = 1;
            cateId = item.getId();
            mTabEntities.clear();
            mTabEntities.add(new TabEntity(mDtoList.get(0).getName(), 0, 0));
            mTabEntities.add(new TabEntity(item.getName(), R.mipmap.home_arrow_up, R.mipmap.home_arrow_down));
            topMainTab.setTabData(mTabEntities);
            presenter.getTaskList(pageNum, cateId);
        });
        tipAdapter.setListener((position, itemData) -> {
            if (position == 0) {
                if (!Hawk.get(HawkKey.IS_USER_LOGIN, false)) {
                    LoginActivity.open(mContext);
                    return;
                }
                SignInActivity.open(mContext);
            } else {
                WebViewActivity.open(mContext, itemData.getTitle(), itemData.getUrl());
            }
        });
    }

    @Override
    public void showProLoading() {
        showLoading();
    }

    @Override
    public void dimissProLoading() {
        dismissLoading();
    }

    @Override
    public void showErrorMessage(int postCode, String code, String message) {
        showErrorMsg(code, message);
    }

    @OnClick({R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
                SearchTaskActivity.open(mContext);
                break;
        }
    }

    @Override
    public void showBannerList(List<BannerDto> list) {
        mBannerList = list;
        imageUrl.clear();
        for (BannerDto dto : mBannerList) {
            if (dto.getBannerType() == 4) {//如果是榜单轮播图
                Hawk.put(HawkKey.BANNER_IMAGE, dto.getImgUrl());
            }
            imageUrl.add(dto.getImgUrl());
        }
        mBannerlayout.setImages(imageUrl);
        mBannerlayout.start();
    }

    @Override
    public void showClassification(List<ClassificationDto> result) {
        mDtoList = result;
        pageNum = 1;
        if (mDtoList.size() > 0) {
            mTabEntities.clear();
            cateId = mDtoList.get(0).getId();
            mTabEntities.add(new TabEntity(mDtoList.get(0).getName(), 0, 0));
            mTabEntities.add(new TabEntity("筛选任务", R.mipmap.home_arrow_up, R.mipmap.home_arrow_down));
            topMainTab.setTabData(mTabEntities);
            presenter.getTaskList(pageNum, cateId);
        }
    }

    @Override
    public void showTaskList(List<TaskListDto> list, int pageNum) {
        if (pageNum == 1) {
            datas.clear();
        }
        datas.addAll(list);
        mAdpater.notifyDataSetChanged();
        onLoad(list.size());
    }

    @Override
    public void showNavigationList(List<NavigationDto> list) {
        NavigationDto dto = new NavigationDto();
        dto.setId(-1);
        list.add(0, dto);
        tipAdapter.setNewData(list);
    }

    @Override
    public void showRanking(RankDto list) {
        Hawk.put(HawkKey.RANKING, list);
        List<String> messages = new ArrayList<>();
        for (RankDto.RankingDtoBean str : list.getRankingDto()) {
            messages.add(str.getNickName() + "    邀请了" + str.getRecommendNum() + "人    累计获得" + str.getCommission() + "佣金");
        }
        marqueeView.startWithList(messages);
    }

    @Override
    public void showBannerDetails(String result, int position) {
        WebViewActivity.open(mContext, mBannerList.get(position).getTitle(), result);
    }

    public void onLoad(int size) {
        if (mRefLayout == null) {
            return;
        }
        mRefLayout.finishRefreshLoadingMore();
        if (size < 10) {
            mRefLayout.enableLoadMore(false);
        } else {
            mRefLayout.enableLoadMore(true);
        }
    }
}
